<?php
namespace app\service;

use Workerman\Worker;
use Workerman\Connection\TcpConnection;

class WebSocketService
{
    protected $worker;

    public function __construct($address = 'websocket://0.0.0.0:2346')
    {
        $this->worker = new Worker($address);

        // 设置进程数
        $this->worker->count = 4;

        $this->worker->onConnect = function(TcpConnection $connection) {
            echo "New connection\n";
        };

        $this->worker->onMessage = function(TcpConnection $connection, $data) {
            // 处理客户端发送的消息
            $connection->send(json_encode(['type' => 'message', 'content' => 'Hello']));
            echo "send success\n";
        };

        $this->worker->onWorkerStart = function() 
        {
            // 开启一个内部端口，方便内部系统推送数据，Text协议格式 文本+换行符
            $inner_text_worker = new Worker('Text://0.0.0.0:5678');
            $inner_text_worker->onMessage = function($connection, $buffer)
            {
                $ret = $this->pushToAll($buffer);
                // 返回推送结果
                $connection->send($ret ? 'ok' : 'fail');
            };
            $inner_text_worker->listen();
        };

        $this->worker->onClose = function(TcpConnection $connection) {
            echo "Connection closed\n";
        };
    }

    // 启动 WebSocket 服务器
    public function start()
    {
        Worker::runAll();
    }

    // 推送消息到所有客户端
    public function pushToAll($message)
    {
        foreach($this->worker->connections as $connection)
        {
            $connection->send($message);
        }
        return true;
    }

    public function pushOrderStatus($order)
    {
        // 使用 Workerman 推送订单状态
        $context = stream_context_create([
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
            ],
        ]);

        $client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
        if ($client) {
            $message = json_encode([
                    'order_id' => $order->id,
                    'status' => $order->status,
                ])."\n";

            fwrite($client, $message);
            fclose($client);
        }
    }
}
